/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.andersen.web.controller;

import com.andersen.database.entity.EmployeeEntity;
import com.andersen.database.entity.OfficeEntity;
import com.andersen.database.entity.Roles;
import com.andersen.database.entity.UserEntity;
import com.andersen.web.beans.RegisterCommandForm;
import com.andersen.web.validating.RegisterValidator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;

/**
 *
 * @author Corvus 11
 */
@Controller
public class RegisterController extends AbstractController{

    @Autowired
    RegisterValidator validator;
    
    @ModelAttribute(value = "officeNameList")
    public List<OfficeEntity> populateOfficeNameList() {
        return officeService.getOfficeList();
    }

    
    @RequestMapping(value="/a_register", method= RequestMethod.GET) 
    public String openRegisterPage(ModelMap map, 
                                  @RequestParam(required = true, value = "employeeId") String employeeId,
                                  HttpServletResponse response) {
        
        LOG.info("[/a_register] mapped.");
        
        long id = Long.valueOf(employeeId);
        
        RegisterCommandForm form = new RegisterCommandForm();
        form.setEmployeeId(id);
        
        if (id != -1) {
            EmployeeEntity employee = employeeService.getEmployee(id);
            form.setFio(employee.getSurnameNamePatronymic());
        } 
        
        /*EmployeeEntity employee = employeeService.getEmployee(id);
        
        if (employee == null) {
            LOG.error("Невозможно загрузить объект Employee с id " + employeeId);
            return "register";
        }
        
        Object[] tokens = {employee.getSurname(),employee.getName(),employee.getPatronymic()};
        String fio = StringUtils.join(tokens," ");
        
        */
        map.addAttribute("registerCommandForm",form);

        return "templates/dialog_register";
    }
    
    @RequestMapping(value = "/a_get_employees_from", method = RequestMethod.GET)
    public @ResponseBody void getEmployeesFrom(@RequestParam(value = "officeId", required = true) String employeeId,
                                               HttpServletResponse response) throws IOException {
        long id = Long.parseLong(employeeId);
        ArrayList<EmployeeEntity> empl = 
                employeeService.getEmployeesForAccounts(id);
        JSONArray arr = new JSONArray();
        for(int i=0;i<empl.size();i++) {
            JSONObject jobj = new JSONObject();
            jobj.accumulate("id", empl.get(i).getId());
            jobj.accumulate("surnameNamePatronymic", empl.get(i).getSurnameNamePatronymic());
            arr.add(jobj);
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(arr.toString());
        response.setStatus(200);
        LOG.info(arr.toString());
    }
    
    /*@ModelAttribute("officeNameList")
    public List<OfficeEntity> populateOfficeNameList() {
        return officeService.getOfficeList();
    }*/
    
    @RequestMapping(value = "/a_register", method= RequestMethod.POST)
    public String registerNewUser(@ModelAttribute("registerCommandForm") RegisterCommandForm command,
            BindingResult result, SessionStatus status, HttpServletResponse response) throws IOException {
        
        command.setValidationError(false);
        
        validator.validate(command, result);
        if (result.hasErrors()) { //ошибка валидации
            response.setStatus(200);
            command.setValidationError(true);
            command.setEmployeeId(-1);
            return "templates/dialog_register";
        }
        //валидация прошла
            UserEntity ent = new UserEntity();
            ent.setActive(true);
            ent.setEmployeeId(command.getEmployeeId());
            ent.setLogin(command.getLogin());
            Md5PasswordEncoder encoder = new Md5PasswordEncoder();
            ent.setPassword(encoder.encodePassword(command.getPassword(), null));
            ArrayList<String> roles = new ArrayList<String>();
            roles.add(Roles.USER);
            if (command.isHr()) roles.add(Roles.HR);
            if (command.isManager()) roles.add(Roles.MANAGER);
            
            long id = userService.insertUser(ent);
            
            for(String r : roles)
                userService.addRole(id, r);
            
            if (id<=0) {
                response.setStatus(500);
                return "templates/dialog_register";
            
            }
            command.setValidationError(false);
            response.setStatus(200);
            return "templates/dialog_register";
        }
    }
            

